﻿#include "additem.h"
#include "ui_additem.h"

AddItem::AddItem(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddItem)
{
    ui->setupUi(this);

    table=RES_ACG;
    updateCategory();
}

AddItem::~AddItem()
{
    delete ui;
}

void AddItem::updateCategory()
{
    if(ui->categories->count() != 0)
        ui->categories->clear();

    QStringList items=sp_getCategory(table);
    if(!items.isEmpty())
        ui->categories->addItems(items);

    ui->categories->addItem(MANUAL_INPUT);
    ui->categories->setCurrentIndex(-1);
}

bool AddItem::addItem(const QString &category,
                      const QString &label,
                      const QString &detail,
                      const QString &addition,
                      const QString &ref)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (category,label,detail,addition,ref) values (?,?,?,?,?)")
                  .arg(table));
    query.addBindValue(category);
    query.addBindValue(label);
    query.addBindValue(detail);
    query.addBindValue(addition);
    query.addBindValue(ref);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void AddItem::setCategory(const QString &category)
{
    ui->categories->setCurrentText(category);
}

void AddItem::on_btn_submit_clicked()
{
    QString category=ui->category->text().trimmed();
    if(category.isEmpty())
    {
        MESSAGE_CATEGORY_EMPTY
    }

    QString label=ui->label->text().trimmed();
    QString detail=ui->detail->text().trimmed();
    if(label.isEmpty() || detail.isEmpty())
    {
        MESSAGE_DETAIL_EMPTY
    }

    QString addition=ui->addition->text().trimmed();
    QString ref=ui->ref->text().trimmed();
    if(addItem(category,label,detail,addition,ref))
        accept();
    else
        MESSAGE_CANNOT_SUBMIT
}

void AddItem::on_categories_currentTextChanged(const QString &text)
{
    if(text == MANUAL_INPUT)
    {
        ui->category->clear();
        ui->category->setEnabled(true);
    }
    else
    {
        ui->category->setText(text);
        ui->category->setEnabled(false);
    }
}

void AddItem::on_btn_labelP_clicked()
{
    QString label=qApp->clipboard()->text().trimmed();
    ui->label->setText(label);
}

void AddItem::on_btn_detailP_clicked()
{
    QString detail=qApp->clipboard()->text().trimmed();
    ui->detail->setText(detail);
}

void AddItem::on_btn_additionP_clicked()
{
    QString addition=qApp->clipboard()->text().trimmed();
    ui->addition->setText(addition);
}

void AddItem::on_btn_refP_clicked()
{
    QString ref=qApp->clipboard()->text().trimmed();
    ui->ref->setText(ref);
}
